package pers.xhh.shopapi.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.common.ResultCode;
import pers.xhh.shopapi.dao.MiRoleDao;
import pers.xhh.shopapi.entity.MiManagerEntity;
import pers.xhh.shopapi.entity.MiRoleEntity;
import pers.xhh.shopapi.entity.to.role.MiRoleRightsTo;
import pers.xhh.shopapi.entity.to.role.MiRoleTo;
import pers.xhh.shopapi.entity.vo.permission.MiPermissionTreeVo;
import pers.xhh.shopapi.entity.vo.role.MiRoleListVo;
import pers.xhh.shopapi.service.MiManagerService;
import pers.xhh.shopapi.service.MiPermissionService;
import pers.xhh.shopapi.service.MiRoleService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
@Service
public class MiRoleServiceImpl extends ServiceImpl<MiRoleDao, MiRoleEntity> implements MiRoleService {

    @Autowired
    MiManagerService miManagerService;

    @Autowired
    MiRoleService miRoleService;

    @Autowired
    MiPermissionService miPermissionService;

    @Override
    public Mi listRoles(String authorization) {
        // ->能通过拦截器,authorization正确
        // 根据authorization拿到当前用户id
        String userId = JWT.decode(authorization).getAudience().get(0);
        MiManagerEntity byId = miManagerService.getById(userId);
        // 如果当前用户为超级管理员,返回所有,且状态为启用
        Integer roleId = byId.getRoleId();
        Integer mgState = byId.getMgState();
        if(roleId == 0 && mgState == 1){
            // 超级管理员
            List<MiRoleEntity> list =
                    miRoleService.list(new QueryWrapper<>());

            if(list.size() > 0){
                List<MiRoleListVo> roleListVos = list.stream().map(item -> {
                    MiRoleListVo miRoleListVo = new MiRoleListVo();
                    miRoleListVo.setId(item.getRoleId());
                    miRoleListVo.setRoleName(item.getRoleName());
                    miRoleListVo.setRoleDesc(item.getRoleDesc());
                    // 查询对应的权限
                    List<MiPermissionTreeVo> permissionTreeByIds = new ArrayList<>();
                    String psIds = item.getPsIds();
                    if (psIds != null) {
                        List<String> collect = Arrays.stream(psIds.split(",")).collect(Collectors.toList());
                        if (collect.size() > 0) {
                            permissionTreeByIds = miPermissionService.getPermissionTreeByIds(collect);
                        }
                    }
                    miRoleListVo.setChildren(permissionTreeByIds);
                    return miRoleListVo;
                }).collect(Collectors.toList());

                return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), roleListVos);
            }
        }


        return Mi.error(ResultCode.ERROR402.getMessage(), ResultCode.ERROR402.getStatus());
    }

    @Override
    public Mi saveRole(MiRoleTo miRoleTo) {
        String roleName = miRoleTo.getRoleName();
        String roleDesc = miRoleTo.getRoleDesc();

        // ->添加角色
        MiRoleEntity miRoleEntity = new MiRoleEntity();
        miRoleEntity.setRoleName(roleName);
        if(roleDesc != null){
            miRoleEntity.setRoleDesc(roleDesc);
        }
        miRoleEntity.setCreateTime(new Date());
        miRoleEntity.setUpdateTime(new Date());

        boolean save = this.save(miRoleEntity);

        if(save){
            Map<String, Object> map = new HashMap<>();
            map.put("roleName", roleName);
            if(roleDesc != null){
                map.put("roleDesc", roleDesc);
            }
            return Mi.ok(ResultCode.SUCCESS1.getMessage(), ResultCode.SUCCESS1.getStatus(),map);
        }
        return Mi.error(ResultCode.ERROR403.getMessage(), ResultCode.ERROR403.getStatus());
    }

    @Override
    public Mi getRoleById(Integer id) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
        }
        MiRoleEntity byId = this.getById(id);
        if(byId != null){
            Map<String, Object> map = new HashMap<>();
            map.put("roleId", byId.getRoleId());
            map.put("roleName", byId.getRoleName());
            map.put("roleDesc", byId.getRoleDesc());
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(),map);
        }

        return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
    }

    @Override
    public Mi updateRoleById(Integer id, MiRoleTo miRoleTo) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
        }
        String roleName = miRoleTo.getRoleName();
        String roleDesc = miRoleTo.getRoleDesc();

        MiRoleEntity miRoleEntity = new MiRoleEntity();
        miRoleEntity.setRoleId(id);
        if(roleDesc != null){
            miRoleEntity.setRoleDesc(roleDesc);
        }
        miRoleEntity.setRoleName(roleName);
        miRoleEntity.setUpdateTime(new Date());

        boolean b = this.updateById(miRoleEntity);
        if(b){
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            if(roleDesc != null){
                map.put("roleName", roleName);
            }
            map.put("roleDesc", roleDesc);
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(),map);
        }
        return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
    }

    @Override
    public Mi deleteRoleById(Integer id) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
        }

        boolean b = this.removeById(id);
        if(b){
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(),map);
        }
        return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
    }

    @Override
    public Mi updateRights(Integer id, MiRoleRightsTo miRoleRightsTo) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
        }
        String rids = miRoleRightsTo.getRids();
        MiRoleEntity roleEntity = new MiRoleEntity();
        roleEntity.setRoleId(id);
        roleEntity.setPsIds(rids);
        boolean b = this.updateById(roleEntity);
        if(b){
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("rids", rids);
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(),map);
        }
        return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
    }

    @Override
    public Mi deleteRights(String authorization, Integer id, Integer rightId) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
        }
        // ->查询id
        MiRoleEntity byId = this.getById(id);
        String psIds = byId.getPsIds();
        if (psIds != null) {
            List<String> collect = Arrays.stream(psIds.split(",")).collect(Collectors.toList());
            for (int i = 0; i < collect.size(); i++) {
                if(collect.get(i).equals("" + rightId)){
                    collect.remove(i);
                }
            }

            String join = "";
            if(collect.size() > 0){
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < collect.size(); i++) {
                    if(i == (collect.size() - 1)){
                        stringBuilder.append(collect.get(i));
                    } else {
                        stringBuilder.append(collect.get(i)).append(",");
                    }
                }
                join = stringBuilder.toString();
            }
            // ->更新
            MiRoleEntity miRoleEntity = new MiRoleEntity();
            miRoleEntity.setRoleId(id);
            miRoleEntity.setPsIds(join);
            miRoleEntity.setUpdateTime(new Date());
            boolean b = this.updateById(miRoleEntity);
            // 更新成功,
            if(b){
                // TODO authorization：返回权限列表暂时不做
                Map<String, Object> map = new HashMap<>();
                map.put("id", id);
                map.put("rids", join);
                return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
            }

        }
        return Mi.error(ResultCode.ERROR405.getMessage(), ResultCode.ERROR405.getStatus());
    }
}
